package top.houry.im.ui.controller;

import javafx.collections.ObservableList;
import javafx.scene.Node;
import javafx.scene.control.*;
import javafx.scene.input.KeyCode;
import javafx.scene.layout.Pane;
import top.houry.im.ui.component.*;
import top.houry.im.ui.component.group_bar_friend.ElementFriendGroupList;
import top.houry.im.ui.component.group_bar_friend.ElementFriendUserList;
import top.houry.im.ui.init.ImUiMainInit;
import top.houry.im.ui.interfaces.ImUiMainEvent;
import top.houry.im.ui.interfaces.ImUiMainMethod;
import top.houry.im.ui.util.CacheUtil;
import top.houry.im.ui.util.Ids;

import java.util.Date;

/**
 * @Desc
 * @Author houruiyang
 * @Date 2022/5/17
 **/
public class ImUiMainController extends ImUiMainInit implements ImUiMainMethod {

    private ImUiMainEvent mainEvent;

    private String userId;

    private String userName;

    public ImUiMainController(ImUiMainEvent mainEvent) {
        this.mainEvent = mainEvent;
        this.move();
        min();               // 最小化
        quit();              // 退出
        barChat();           // 聊天
        barFriend();         // 好友
        doEventTextSend();   // 发送消息事件[键盘]
        doEventTouchSend();  // 发送消息事件[按钮]
        doEventToolFace();   // 表情窗体
//        initNewFriendView();
        addFriendUserList();
//        addFriendGroupList();
    }

    private void addFriendGroupList() {
        ListView<Pane> friendList = lookup("friendList", ListView.class);
        ObservableList<Pane> items = friendList.getItems();

        ElementFriendTag elementFriendTag = new ElementFriendTag("群聊");
        items.add(elementFriendTag.pane());

        ElementFriendGroupList element = new ElementFriendGroupList();
        Pane pane = element.pane();
        items.add(pane);
    }

    private void addFriendUserList() {
        ListView<Pane> friendList = lookup("friendList", ListView.class);
        ObservableList<Pane> items = friendList.getItems();

        ElementFriendTag elementFriendTag = new ElementFriendTag("好友");
        items.add(elementFriendTag.pane());

        ElementFriendUserList element = new ElementFriendUserList();
        Pane pane = element.pane();
        items.add(pane);
    }

    // 最小化
    private void min() {
        this.lookup("group_bar_chat_min", Button.class).setOnAction(event -> {
            this.min();
            this.setIconified(true);
        });
        this.lookup("group_bar_friend_min", Button.class).setOnAction(event -> {
            this.min();
            this.setIconified(true);
        });
    }

    /**
     * 退出
     */
    private void quit() {

        this.lookup("group_bar_chat_close", Button.class).setOnAction(event -> {
            mainEvent.closeMainUi();
            this.close();
            System.exit(0);
        });
        this.lookup("group_bar_friend_close", Button.class).setOnAction(event -> {
            mainEvent.closeMainUi();
            this.close();
            System.exit(0);
        });
    }

    // 聊天
    private void barChat() {
        Button barChat = this.lookup("bar_chat", Button.class);
        Pane groupBarChat = this.lookup("group_bar_chat", Pane.class);
        barChat.setOnAction(event -> {
            switchBarChat(barChat, groupBarChat, true);
            switchBarFriend(this.lookup("bar_friend", Button.class), this.lookup("group_bar_friend", Pane.class), false);
        });
        barChat.setOnMouseEntered(event -> {
            boolean visible = groupBarChat.isVisible();
            if (!visible) {
                barChat.setStyle("-fx-background-image: url('/fxml/main/img/system/chat_1.png')");
            }
        });
        barChat.setOnMouseExited(event -> {
            boolean visible = groupBarChat.isVisible();
            if (!visible) {
                barChat.setStyle("-fx-background-image: url('/fxml/main/img/system/chat_0.png')");
            }
        });
    }

    // 好友
    private void barFriend() {
        Button bar_friend = this.lookup("bar_friend", Button.class);
        Pane group_bar_friend = this.lookup("group_bar_friend", Pane.class);
        bar_friend.setOnAction(event -> {
            switchBarChat(this.lookup("bar_chat", Button.class), this.lookup("group_bar_chat", Pane.class), false);
            switchBarFriend(bar_friend, group_bar_friend, true);
        });
        bar_friend.setOnMouseEntered(event -> {
            boolean visible = group_bar_friend.isVisible();
            if (visible) {
                return;
            }
            bar_friend.setStyle("-fx-background-image: url('/fxml/main/img/system/friend_1.png')");
        });
        bar_friend.setOnMouseExited(event -> {
            boolean visible = group_bar_friend.isVisible();
            if (visible) {
                return;
            }
            bar_friend.setStyle("-fx-background-image: url('/fxml/main/img/system/friend_0.png')");
        });
    }

    // 切换：bar_chat
    private void switchBarChat(Button barChat, Pane groupBarChat, boolean toggle) {
        if (toggle) {
            barChat.setStyle("-fx-background-image: url('/fxml/main/img/system/chat_1.png')");
            groupBarChat.setVisible(true);
        } else {
            barChat.setStyle("-fx-background-image: url('/fxml/main/img/system/chat_0.png')");
            groupBarChat.setVisible(false);
        }
    }

    // 切换：bar_friend
    private void switchBarFriend(Button barFriend, Pane groupBarFriend, boolean toggle) {
        if (toggle) {
            barFriend.setStyle("-fx-background-image: url('/fxml/main/img/system/friend_2.png')");
            groupBarFriend.setVisible(true);
        } else {
            barFriend.setStyle("-fx-background-image: url('/fxml/main/img/system/friend_0.png')");
            groupBarFriend.setVisible(false);
        }
    }

    // 好友；开启与好友发送消息 [点击发送消息时候触发 -> 添加到对话框、选中、展示对话列表]
    public void doEventOpenFriendUserSendMsg(Button sendMsgButton, String userFriendId, String userFriendNickName, String userFriendHead) {
        sendMsgButton.setOnAction(event -> {
            // 1. 添加好友到对话框
            this.addTalkBox(0, 0, userFriendId, userFriendNickName, userFriendHead, null, null, true);
            // 2. 切换到对话框窗口
            switchBarChat(this.lookup("bar_chat", Button.class), this.lookup("group_bar_chat", Pane.class), true);
            switchBarFriend(this.lookup("bar_friend", Button.class), this.lookup("group_bar_friend", Pane.class), false);
            // 3. 事件处理；填充到对话框
//            this.doEventAddTalkUser(this.userId, userFriendId);
        });
    }

    // 群组；开启与群组发送消息
    public void doEventOpenFriendGroupSendMsg(Button sendMsgButton, String groupId, String groupName, String groupHead) {
//        sendMsgButton.setOnAction(event -> {
//            // 1. 添加好友到对话框
//            chatMethod.addTalkBox(0, 1, groupId, groupName, groupHead, null, null, true);
//            // 2. 切换到对话框窗口
//            switchBarChat(chatInit.lookup("bar_chat", Button.class), chatInit.lookup("group_bar_chat", Pane.class), true);
//            switchBarFriend(chatInit.lookup("bar_friend", Button.class), chatInit.lookup("group_bar_friend", Pane.class), false);
//            // 3. 事件处理；填充到对话框
//            chatEvent.doEventAddTalkGroup(chatInit.userId, groupId);
//        });
    }

    // 发送消息事件[键盘]
    private void doEventTextSend() {
        TextArea txt_input = this.lookup("txt_input", TextArea.class);
        txt_input.setOnKeyPressed(event -> {
            if (event.getCode().equals(KeyCode.ENTER)) {
                event.consume();
                doEventSendMsg();
            }
        });
    }

    // 发送消息事件[按钮]
    private void doEventTouchSend() {
        Label touch_send = this.lookup("touch_send", Label.class);
        touch_send.setOnMousePressed(event -> {
            doEventSendMsg();
        });
    }

    private void doEventSendMsg() {
        TextArea txt_input = this.lookup("txt_input", TextArea.class);
        MultipleSelectionModel selectionModel = this.lookup("talkList", ListView.class).getSelectionModel();
        Pane selectedItem = (Pane) selectionModel.getSelectedItem();
        if (null == selectedItem) {
            return;
        }
        // 对话信息
        TalkBoxData talkBoxData = (TalkBoxData) selectedItem.getUserData();

        String msg = txt_input.getText();
        if (null == msg || "".equals(msg) || "".equals(msg.trim())) {
            // TODO 加提示信息
            return;
        }
        Date msgDate = new Date();
        // 发送消息
//        chatEvent.doSendMsg(chatInit.userId, talkBoxData.getTalkId(), talkBoxData.getTalkType(), msg, 0, msgDate);
        mainEvent.sendMsg(userId, talkBoxData.getTalkId(), talkBoxData.getTalkId(), talkBoxData.getTalkType(), msg);
        // 发送事件给自己添加消息
        this.addTalkMsgRight(talkBoxData.getTalkId(), msg, 0, msgDate, true, true, false);
        txt_input.clear();
    }

    // 表情
    private void doEventToolFace() {
//        FaceController face = new FaceController(chatInit, chatInit, chatEvent, chatMethod);
//        Button tool_face = chatInit.lookup("tool_face", Button.class);
//        tool_face.setOnMousePressed(event -> {
//            face.doShowFace(chatMethod.getToolFaceX(), chatMethod.getToolFaceY());
//        });
    }


    private void initNewFriendView() {
        ListView<Pane> friendList = this.lookup("friendList", ListView.class);
        ObservableList<Pane> items = friendList.getItems();

        ElementFriendTag elementFriendTag = new ElementFriendTag("新的朋友");
        items.add(elementFriendTag.pane());

        ElementFriendLuck element = new ElementFriendLuck();
        Pane pane = element.pane();
        items.add(pane);

        // 面板填充和事件
        pane.setOnMousePressed(event -> {
            Pane friendLuckPane = element.friendLuckPane();
            setContentPaneBox("itstack-naive-chat-ui-chat-friend-luck", "新的朋友", friendLuckPane);
            this.clearViewListSelectedAll(this.lookup("userListView", ListView.class), this.lookup("groupListView", ListView.class));
            ListView<Pane> listView = element.friendLuckListView();
            listView.getItems().clear();
            //chatEvent.addFriendLuck(chatInit.userId, listView);
        });

        // 搜索框事件
        TextField friendLuckSearch = element.friendLuckSearch();

        // 键盘事件；搜索好友
        friendLuckSearch.setOnKeyPressed(event -> {
            if (event.getCode().equals(KeyCode.ENTER)) {
                String text = friendLuckSearch.getText();
                if (null == text) text = "";
                if (text.length() > 30) text = text.substring(0, 30);
                text = text.trim();
                //chatEvent.doFriendLuckSearch(chatInit.userId, text);
                // 搜索清空元素
                element.friendLuckListView().getItems().clear();
            }
        });

    }


    void setContentPaneBox(String id, String name, Node node) {
        // 填充对话列表
        Pane content_pane_box = this.lookup("content_pane_box", Pane.class);
        content_pane_box.setUserData(id);
        content_pane_box.getChildren().clear();
        content_pane_box.getChildren().add(node);
        // 对话框名称
        Label info_name = this.lookup("content_name", Label.class);
        info_name.setText(name);
    }

    @Override
    public void setUserInfo(String userId, String userName) {
        this.userId = userId;
        this.userName = userName;
    }

    @Override
    public void doShow() {
        super.show();
    }

    @Override
    public void addTalkBox(int talkIdx, Integer talkType, String talkId, String talkName, String talkHead, String talkSketch, Date talkDate, Boolean selected) {
        // 填充到对话框
        ListView<Pane> talkList = lookup("talkList", ListView.class);
        // 判断会话框是否有该对象
        ElementTalk elementTalk = CacheUtil.talkMap.get(talkId);
        if (null != elementTalk) {
            Node talkNode = talkList.lookup("#" + Ids.ElementTalkId.createTalkPaneId(talkId));
            if (null == talkNode) {
                talkList.getItems().add(talkIdx, elementTalk.pane());
                // 填充对话框消息栏
                fillInfoBox(elementTalk, talkName);
            }
            if (selected) {
                // 设置选中
                talkList.getSelectionModel().select(elementTalk.pane());
            }
            // 填充对话框消息栏
            fillInfoBox(elementTalk, talkName);
            return;
        }
        // 初始化对话框元素
        ElementTalk talkElement = new ElementTalk(talkId, talkType, talkName, talkHead, talkSketch, talkDate);
        CacheUtil.talkMap.put(talkId, talkElement);
        // 填充到对话框
        ObservableList<Pane> items = talkList.getItems();
        Pane talkElementPane = talkElement.pane();
        if (talkIdx >= 0) {
            items.add(talkIdx, talkElementPane);  // 添加到第一个位置
        } else {
            items.add(talkElementPane);           // 顺序添加
        }
        if (selected) {
            talkList.getSelectionModel().select(talkElementPane);
        }
        // 对话框元素点击事件
        talkElementPane.setOnMousePressed(event -> {
            // 填充消息栏
            fillInfoBox(talkElement, talkName);
            // 清除消息提醒
            Label msgRemind = talkElement.msgRemind();
            msgRemind.setUserData(new RemindCount(0));
            msgRemind.setVisible(false);
        });
        // 鼠标事件[移入/移出]
        talkElementPane.setOnMouseEntered(event -> {
            talkElement.delete().setVisible(true);
        });
        talkElementPane.setOnMouseExited(event -> {
            talkElement.delete().setVisible(false);
        });
        // 填充对话框消息栏
        fillInfoBox(talkElement, talkName);
        // 从对话框中删除
        talkElement.delete().setOnMouseClicked(event -> {
            talkList.getItems().remove(talkElementPane);
            lookup("info_pane_box", Pane.class).getChildren().clear();
            lookup("info_pane_box", Pane.class).setUserData(null);
            lookup("info_name", Label.class).setText("");
            talkElement.infoBoxList().getItems().clear();
            talkElement.clearMsgSketch();
            //chatEvent.doEventDelTalkUser(super.userId, talkId);
        });
    }

    @Override
    public void addTalkMsgUserLeft(String talkId, String msg, Integer msgType, Date msgData, Boolean idxFirst, Boolean selected, Boolean isRemind) {
        ElementTalk talkElement = CacheUtil.talkMap.get(talkId);
        ListView<Pane> listView = talkElement.infoBoxList();
        TalkData talkUserData = (TalkData) listView.getUserData();
        Pane left = new ElementInfoBox().left(talkUserData.getTalkName(), talkUserData.getTalkHead(), msg, msgType);
        // 消息填充
        listView.getItems().add(left);
        // 滚动条
        listView.scrollTo(left);
        talkElement.fillMsgSketch(0 == msgType ? msg : "[表情]", msgData);
        // 设置位置&选中
//        chatView.updateTalkListIdxAndSelected(0, talkElement.pane(), talkElement.msgRemind(), idxFirst, selected, isRemind);
    }


//    void updateTalkListIdxAndSelected(int talkType, Pane talkElementPane, Label msgRemindLabel, Boolean idxFirst, Boolean selected, Boolean isRemind) {
//        // 对话框ID、好友ID
//        TalkBoxData talkBoxData = (TalkBoxData) talkElementPane.getUserData();
//        // 填充到对话框
//        ListView<Pane> talkList = this.lookup("talkList", ListView.class);
//        // 对话空为空，初始化[置顶、选中、提醒]
//        if (talkList.getItems().isEmpty()) {
//            if (idxFirst) {
//                talkList.getItems().add(0, talkElementPane);
//            }
//            if (selected) {
//                // 设置对话框[√选中]
//                talkList.getSelectionModel().select(talkElementPane);
//            }
//            isRemind(msgRemindLabel, talkType, isRemind);
//            return;
//        }
//        // 对话空不为空，判断第一个元素是否当前聊天Pane
//        Pane firstPane = talkList.getItems().get(0);
//        // 判断元素是否在首位，如果是首位可返回不需要重新设置首位
//        if (talkBoxData.getTalkId().equals(((TalkBoxData) firstPane.getUserData()).getTalkId())) {
//            Pane selectedItem = talkList.getSelectionModel().getSelectedItem();
//            // 选中判断；如果第一个元素已经选中[说明正在会话]，那么清空消息提醒
//            if (null == selectedItem){
//                isRemind(msgRemindLabel, talkType, isRemind);
//                return;
//            }
//            TalkBoxData selectedItemUserData = (TalkBoxData) selectedItem.getUserData();
//            if (null != selectedItemUserData && talkBoxData.getTalkId().equals(selectedItemUserData.getTalkId())) {
//                clearRemind(msgRemindLabel);
//            } else {
//                isRemind(msgRemindLabel, talkType, isRemind);
//            }
//            return;
//        }
//        if (idxFirst) {
//            talkList.getItems().remove(talkElementPane);
//            talkList.getItems().add(0, talkElementPane);
//        }
//        if (selected) {
//            // 设置对话框[√选中]
//            talkList.getSelectionModel().select(talkElementPane);
//        }
//        isRemind(msgRemindLabel, talkType, isRemind);
//    }

    @Override
    public void addTalkMsgRight(String talkId, String msg, Integer msgType, Date msgData, Boolean idxFirst, Boolean selected, Boolean isRemind) {
        ElementTalk talkElement = CacheUtil.talkMap.get(talkId);
        ListView<Pane> listView = talkElement.infoBoxList();
        Pane right = new ElementInfoBox().right("userNickName", "userHead", msg, msgType);
        // 消息填充
        listView.getItems().add(right);
        // 滚动条
        listView.scrollTo(right);
        talkElement.fillMsgSketch(0 == msgType ? msg : "[表情]", msgData);
        // 设置位置&选中
//        chatView.updateTalkListIdxAndSelected(0, talkElement.pane(), talkElement.msgRemind(), idxFirst, selected, isRemind);
    }

    @Override
    public void addFriendUser(boolean selected, String userFriendId, String userFriendNickName, String userFriendHead) {
        ElementFriendUser friendUser = new ElementFriendUser(userFriendId, userFriendNickName, userFriendHead);
        Pane pane = friendUser.pane();
        // 添加到好友列表
        ListView<Pane> userListView = lookup("userListView", ListView.class);
        ObservableList<Pane> items = userListView.getItems();
        items.add(pane);
        userListView.setPrefHeight(80 * items.size());
        lookup("friendUserList", Pane.class).setPrefHeight(80 * items.size());
        // 选中
        if (selected) {
            userListView.getSelectionModel().select(pane);
        }

        // 好友，内容框[初始化，未装载]，承载好友信息内容，点击按钮时候填充
        Pane detailContent = new Pane();
        detailContent.setPrefSize(850, 560);
        detailContent.getStyleClass().add("friendUserDetailContent");
        ObservableList<Node> children = detailContent.getChildren();

        Button sendMsgButton = new Button();
        sendMsgButton.setId(userFriendId);
        sendMsgButton.getStyleClass().add("friendUserSendMsgButton");
        sendMsgButton.setPrefSize(176, 50);
        sendMsgButton.setLayoutX(337);
        sendMsgButton.setLayoutY(450);
        sendMsgButton.setText("发送消息");
        this.doEventOpenFriendUserSendMsg(sendMsgButton, userFriendId, userFriendNickName, userFriendHead);
        children.add(sendMsgButton);
        // 添加监听事件
        pane.setOnMousePressed(event -> {
//            clearViewListSelectedAll(lookup("friendList", ListView.class), lookup("groupListView", ListView.class));
            this.setContentPaneBox(userFriendId, userFriendNickName, detailContent);
        });
        this.setContentPaneBox(userFriendId, userFriendNickName, detailContent);
    }

    //
//    /**
//     * 私有方法
//     * 填充对话框消息内容
//     *
//     * @param talkElement 对话框元素
//     * @param talkName    对话框名称
//     */
    private void fillInfoBox(ElementTalk talkElement, String talkName) {
        String talkId = talkElement.pane().getUserData().toString();
        // 填充对话列表
        Pane info_pane_box = lookup("info_pane_box", Pane.class);
        String boxUserId = (String) info_pane_box.getUserData();
        // 判断是否已经填充[talkId]，当前已填充则返回
        if (talkId.equals(boxUserId)) return;
        ListView<Pane> listView = talkElement.infoBoxList();
        info_pane_box.setUserData(talkId);
        info_pane_box.getChildren().clear();
        info_pane_box.getChildren().add(listView);
        // 对话框名称
        Label info_name = lookup("info_name", Label.class);
        info_name.setText(talkName);
    }


}



